import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "..";
import { getSysMenusList, getSysMenusSelectTree } from "@/api/sys/sysMenus";

const initialState = {
  menusLoading: false,
  menusList: [] as SysMenuEntityType[],
  menusSearchParams: {
    name: "",
    status: "",
  } as SysMenuListParams,
  isShowMenusModal: {
    show: false,
    // 1 新增 2 修改
    mode: 1,
    title: "新增",
    data: {} as Partial<SysMenuEntityType>,
  },
  menusSelectTree: [] as SysMenuEntityType[],
};

export const get_sys_menus_list = createAsyncThunk<
  SysMenuEntityType[],
  SysMenuListParams
>("get/get_sys_menus_list", async (params: SysMenuListParams) => {
  return await getSysMenusList(params);
});

export const get_sys_menus_select_tree = createAsyncThunk(
  "get/get_sys_menus_select_tree",
  async () => {
    return await getSysMenusSelectTree();
  }
);

const sysMenusSlice = createSlice({
  name: "sysMenus",
  initialState,
  reducers: {
    set_is_show_menus_modal: (state, action) => {
      state.isShowMenusModal = action.payload;
    },
    set_menus_search_params: (state, action) => {
      state.menusSearchParams = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(get_sys_menus_list.pending, (state) => {
        state.menusLoading = true;
      })
      .addCase(get_sys_menus_list.fulfilled, (state, action) => {
        state.menusLoading = false;
        state.menusList = action.payload;
      });
  },
});

export const select_menus_list = (state: RootState) => state.sysMenus.menusList;
export const select_menus_loading = (state: RootState) =>
  state.sysMenus.menusLoading;
export const select_is_show_menus_modal = (state: RootState) =>
  state.sysMenus.isShowMenusModal;

export const select_menus_search_params = (state: RootState) =>
  state.sysMenus.menusSearchParams;
export const select_menus_select_tree = (state: RootState) =>
  state.sysMenus.menusSelectTree;

export const { set_is_show_menus_modal, set_menus_search_params } =
  sysMenusSlice.actions;

export default sysMenusSlice.reducer;
